//
//  HMComposeView.swift
//  Weibo22
//
//  Created by Apple on 16/12/7.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
import pop

//  点击加号按钮的罩层视图
class HMComposeView: UIView {

    //  截屏图片视图
    private lazy var imageView: UIImageView = UIImageView()
    //  存放6个按钮的数组
    private lazy var composeButtonArray: [HMComposeButton] = [HMComposeButton]()
    //  目标控制器
    private var target: UIViewController?
    //  获取plist文件中数据
    private lazy var composeModelArray: [HMComposeMenu] = self.loadComposePlistData()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //  设置视图大小
        self.size = CGSize(width: ScreenWidth, height: ScreenHeight)
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
    
        backgroundColor = RandomColor()
        
        addSubview(imageView)
        imageView.snp_makeConstraints { (make) in
            make.top.equalTo(self)
            make.leading.equalTo(self)
            make.size.equalTo(self)
        }
        //  处理图片模糊效果
        imageView.image = screenShot().applyLightEffect()
        
        addChildButton()
        
       
        
    }
    
    private func addChildButton() {
        //  按钮的宽度和高度
        let buttonWidth: CGFloat = 80
        let buttonHeight: CGFloat = 100
        //  每项按钮的间距
        let buttonItemMargin: CGFloat = (width - 3 * buttonWidth) / 4
        
        for i in 0..<composeModelArray.count {
            let button = HMComposeButton()
            button.tag = i
            //  点击按钮事件
            button.addTarget(self, action: #selector(btnAction(btn:)), for: .touchUpInside)
            
            //  计算列索引
            let colIndex = i % 3
            //  计算行的索引
            let rowIndex = i / 3
            
            //  设置x坐标
            button.x = CGFloat(colIndex) * buttonWidth + CGFloat(colIndex + 1) * buttonItemMargin
            //  设置Y坐标
            button.y = CGFloat(rowIndex) * buttonHeight + CGFloat(rowIndex) * buttonItemMargin + ScreenHeight
            let model = composeModelArray[i]
            button.setImage(UIImage(named: model.icon!), for: .normal)
            button.setTitle(model.title!, for: .normal)
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
            
            addSubview(button)
            
            composeButtonArray.append(button)
        }
        
        
        
    
    }
    
    
    //  MARK: -- 点击撰写菜单按钮处理事件
    @objc private func btnAction(btn: HMComposeButton) {
        
        
        UIView.animate(withDuration: 0.25, animations: {
            
            for button in self.composeButtonArray {
                button.alpha = 0.2
                if button == btn {
                    // 表示点击的按钮,让其放大
                    button.transform = CGAffineTransform(scaleX: 2, y: 2)
                    
                } else {
                    // 表示执行缩小动画
                    button.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
                }
                
            }
            
            
        }, completion: { (_)-> Void in
        
            
            UIView.animate(withDuration: 0.25, animations: { 
                
                for button in self.composeButtonArray {
                    button.alpha = 1
                    //  重置按钮
                    button.transform = CGAffineTransform.identity
                }
                
                
            }, completion: { (_) -> Void in
                
                //  弹出控制器
                
                
                //  HMComposeViewController
                //  问题1- 直接通过(自定义的)类名获取class 不可以,打印nil -> 需要加上命名空间
                //  通过类型获取类名字符串(Weibo22.HMComposeViewController), 自定义的类获取的类名会有这个命名空间
//                let aa = NSStringFromClass(HMComposeViewController.self)
//                print(aa)
                
                
//                let type = HMComposeViewController.self
                //  转成指定类型,然后创建实例
                let model = self.composeModelArray[btn.tag]
                let classType = NSClassFromString(model.className!) as! UIViewController.Type
                
                //  创建实例
                let vc = classType.init()
                let nav = HMNavigationController(rootViewController: vc)                
                self.target?.present(nav, animated: true, completion: {
                    //  弹出后删除当前视图
                    self.removeFromSuperview()
                })
                
                
                
                
            })
            
            
            
        })
        
        
        
        
    }
    
    
    //  开始弹簧动画效果
    private func startAnimation(isup: Bool) {
        
        //  如果向下动画,那么数组反转
        if isup == false {
            composeButtonArray = composeButtonArray.reversed()
        }
        
        
        for (i, button) in composeButtonArray.enumerated() {
            //  创建弹簧动画对象
            let popSpringAnimation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            if isup {
                //  动画执行的目的地
                popSpringAnimation?.toValue = CGPoint(x: button.centerX, y: button.centerY - 350)
            } else {
                //  动画执行的目的地
                popSpringAnimation?.toValue = CGPoint(x: button.centerX, y: button.centerY + 350)
            }
            
            //  设置弹簧抖动幅度 [0-20]
            popSpringAnimation?.springBounciness = 10
            //  设置弹簧初始速度 [0-20]
            popSpringAnimation?.springSpeed = 10
            //  设置开始时间,完成动画的时间间隔
            //  CACurrentMediaTime 系统的绝对时间->(开机的时间距离现在的一个时间差)
            popSpringAnimation?.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            //  执行动画
            button.pop_add(popSpringAnimation, forKey: nil)
        
        }
        
        
    }
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        startAnimation(isup: false)
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3, execute: {
            self.removeFromSuperview()
        })
        
        
        


    }
    
    //  读取菜单信息plist文件数据
    private func loadComposePlistData() -> [HMComposeMenu] {
        
        //  获取文件路径
        let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        
        //  加载plist文件数据
        let dicArray = NSArray(contentsOfFile: path)! as! [[String: Any]]
        
        //  字典转模型使用YYModel
        
        let modelArray =  NSArray.yy_modelArray(with: HMComposeMenu.self, json: dicArray) as! [HMComposeMenu]
        
        return modelArray
        
    
    }
    
    
    
    func show(target: UIViewController) {
    
        //  设置目标控制器
        self.target = target
        //  不能把当前视图添加到window上因为模态出来的控制器会挡住
//        let window = UIApplication.shared.windows.last!
        
        
        
        target.view.addSubview(self)
        //  执行向上的弹簧动画
        startAnimation(isup: true)
    }
    
    
    
    
    //  截屏操作
    func screenShot() -> UIImage {
        
        //  开启图片上下文
        let window = UIApplication.shared.keyWindow!
        UIGraphicsBeginImageContext(window.size)
        
        //  截图操作
        //  afterScreenUpdates是否等到屏幕更新去截图
        //  rect表示截取的区域
        window.drawHierarchy(in: CGRect(origin: CGPoint.zero, size: window.size), afterScreenUpdates: false)
        //  在图片上下文中获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        
        
        //  结束图片上下文
        UIGraphicsEndImageContext()
        
        return image!
        
        
        
        
    }
    
    
    

}
